var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var fs = require('fs');
// var path = './public/images/'

// 创建当天文件夹
const year = new Date().getFullYear();
const mouth = (new Date().getMonth()) + 1;
const day = new Date().getDate();

// 本地
// const path = `./public/images/${year}${(mouth.toFixed(0)).padStart(2, '0')}${(day.toFixed(0)).padStart(2, '0')}/`; // 当天日期的 文件夹
// 服务器
const path = `/uploadFile/${year}${(mouth.toFixed(0)).padStart(2, '0')}${(day.toFixed(0)).padStart(2, '0')}/`; // 当天日期的 文件夹
if(!fs.existsSync(path)) {
    fs.mkdirSync(path);
}
// 上传图片 UploadFile
router.post('/upload', (req, res, next) => {
    //设置编码格式和上传路径。默认上传路径是os.tmpdir()，可以启动node环境输入查看
    var form = new multiparty.Form({encoding: 'utf-8', uploadDir: path});

    form.parse(req, function(err, fields, files) {
        var filesTmp = JSON.stringify(files);
        // console.log(filesTm  p)
        if(err){
            console.log('parse error: ' + err);
        } else {
            for (var i in files.file) {
                var inputFile = files.file[i]; 
                console.log(inputFile)
                var uploadedPath = inputFile.path;
                var dstPath = path + inputFile.originalFilename;
                //重命名为真实文件名
                fs.rename(uploadedPath, dstPath, function(err) {
                    if (err) {
                        res.send(err);
                        console.log('rename error: ' + err);
                    } else {
                        // imgTitle = inputFile.originalFilename;
                        // imgPath = dstPath;
                        // imgLink = 'www.bestzsyl.cn/api/nodeapi/'
                        var result = { status: 200, data: {
                            imgTitle: inputFile.originalFilename,
                            imgPath: dstPath,
                            imgLink: `www.bestzsyl.cn${dstPath}`
                        } };
                        res.send(result);
                    }
                });
            }
        }
    }); 
})

module.exports = router;
